package com.edgar.baselibrary.utils;

import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import java.util.UUID;

/**
 * Created by xiexiang on 2015/8/28.
 */
public final class DeviceUtils {
    private static final String TAG = DeviceUtils.class.getSimpleName();
    private static final String VIRTUAL_DEVICE_ID = "00000000000000";
    private static String sDeviceId;

    private DeviceUtils(){}

    public static String getDeviceId(Context context){
        synchronized (DeviceUtils.class){
            if(!isEmpty(sDeviceId))return sDeviceId;
            TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            sDeviceId = telephonyManager.getDeviceId();
            String androidId = Settings.Secure.getString(context.getContentResolver(),Settings.Secure.ANDROID_ID);
            if(VIRTUAL_DEVICE_ID.equals(sDeviceId)){
                //模拟器设备
                sDeviceId = UUID.randomUUID().toString();
            } else if(isEmpty(sDeviceId)){
                sDeviceId = androidId;
                if(isEmpty(sDeviceId)){
                    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD_MR1){
                        sDeviceId = Build.SERIAL;
                    } else {
                        sDeviceId = getMacAddress(context);
                    }
                }
            }
            return sDeviceId;
        }
    }

    private static String getMacAddress(Context context){
        WifiInfo wifiInfo = getWifiManager(context).getConnectionInfo();
        if(wifiInfo != null){
            return wifiInfo.getMacAddress();
        }
        return "";
    }

    private static WifiManager getWifiManager(Context context){
        return (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
    }

    public static boolean isEmpty(String str){
        return TextUtils.isEmpty(str);
    }
}
